define(function (require) {
var zsApp = require('app');  
zsApp.controller( 'userPersonalController',["$scope","$http","$state","$stateParams","$window","$timeout", "$rootScope","promptCache","selectCache",function($scope,$http,$state,$stateParams,$window,$timeout,$rootScope,promptCache,selectCache){
		$(".modal-backdrop").remove();
		//ID
		$scope.userId = [];
		//Name
		$scope.userName =[];
		// 状态
		$scope.status = [];
		// 详情
		$scope.userDetailsArray = {};
		// 修改
		$scope.userInfo = {};
		

		//用户状态select
		$scope.user_statusList = [{"id":0,"name":"禁用"},{"id":1,"name":"启用"}];
		//邮箱激活状态select
		$scope.user_isActivateList = [{"id":0,"name":"未激活"},{"id":1,"name":"激活"}];
		//实名认证状态select
		$scope.user_isAutonymList = [{"id":0,"name":"未认证"},{"id":1,"name":"认证"}];
		//性别select
		$scope.user_sexList = [{"id":0,"name":"男"},{"id":1,"name":"女"}];
		
		// 分页
		$scope.paginationConf = {
	        currentPage: 1,
	        totalItems: 100,
	        itemsPerPage: 20,
	        pagesLength: 15,
	        perPageOptions: [10, 20, 30, 40, 50],
	        onChange: function(){
	        	var self = this;
					$http({
						url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/getPusersList',
						method : 'POST',
						data   : {
							pageNumber	:	self.currentPage,
							pageSize  	:	self.itemsPerPage,
							queryType   :  	0,
						},
					}).success(function(res) { 
						
						if(res.result_code != '0000') { 
		                    $scope.isNoData = false;
		                    return false;
		                }
						
						// 表格数据
						$scope.user_tabVal = res.result;
						
						// 遍历每条数据对应的ID
						angular.forEach(res.result, function(obj, i) {
            				$scope.userId[i] = obj.userId;
            				$scope.dataID[i] = obj.userId;
            				$scope.userName[i] = obj.userName;
        				});
        				
        				// 总共有多少条数据
						self.totalItems = res.length;
						
					}).error(function(err) {
						console.log(err);
					});
	        }
	    };
	    
	   		
	// 确定新增（新增一条角色组列表数据）
	$scope.add = function() {
			// 新增角色组名、描述（封装成JSON）
			var uaserAddData = {
				queryType   	:  	1,
              	userName       : $scope.user_userName,
				displayName    : $scope.user_displayName,
				password       : $scope.user_password,
				email          : $scope.user_email,
				registerSource : $scope.user_registerSource,
				portrait       : $scope.user_portrait,
				userFolder     : $scope.user_userFolder,
				status		   : $scope.user_status,
				isActivate     : $scope.user_isActivate,
				isAutonym      : $scope.user_isAutonym,
				userInfos	   : {
					realName		: $scope.real_name,		//真实姓名
					firstName		: $scope.first_name,	//姓
					lastName 		: $scope.last_name,		//名
					identityCard  	: $scope.identity_card,	//身份证
					phone           : $scope.phone,			//电话
					mobile          : $scope.mobile,		//手机
					sex             : $scope.sex,			//性别
					birthday        : $scope.birthday,		//生日	
					province       	: $scope.provincee,		//省份
					city            : $scope.city,	   		//城市
					address         : $scope.address,		//地址
					qq              : $scope.qq,			//qq号
					postCode       	: $scope.post_code,		//邮编
					school          : $scope.school			//学校
				}				
			}
	
			$http({
				url      : $scope.zsUrl+'digitalhome-boss/admin/pusers/add',
				method   : 'POST',
				data     : JSON.stringify(uaserAddData),/* 将JSON发送给服务器 */
				dataType : 'json',
				contentType : 'application/json;charset=UTF-8', 
			}).then(function success(res) {
			console.log(uaserAddData);	
				// 重新加载页面
				// 操作提示
				if( '0000' == res.data.result_code ){
					promptCache.successPrompt(res.data.message);
					$state.go("user.personal",{},{reload:true});
					$("#add").modal("hide");
				}else{
					promptCache.errorPrompt(res.data.message);
				}
				//$state.reload();
				//$state.go("index.personal",{},{reload:true});
			},
			function error(err){
				console.log(err);
			});
			// 关闭窗口
			$('#newlyAdded').modal('hide');
		}
		
	// 详情（用于向用户展示从服务器获取的数据）
	$scope.details = function($event, $index) {
		
		$("#details").modal("show");
		console.log($index);
		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/getPusersInfo/'+$scope.userId[$index]+'',
			method : 'GET',
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8', 
		}).then(function success(res){
				console.log(res.data.result);
				// 向用户展示从服务器获取到的数据
				$scope.details_userName 			= res.data.result.userName;
				$scope.details_displayName 			= res.data.result.displayName;
				$scope.details_password 			= res.data.result.password;
				$scope.details_email				= res.data.result.email;
				$scope.details_registerSource		= res.data.result.registerSource;
				$scope.details_portrait				= res.data.result.portrait ;
				$scope.details_userFolder 			= res.data.result.userFolder;
				$scope.details_status				= res.data.result.status;
				$scope.details_isActivate			= res.data.result.isActivate;
				$scope.details_isAutonym			= res.data.result.isAutonym;
				$scope.details_createDate			= res.data.result.createDate;
				$scope.details_updatePasswordDate   = res.data.result.updatePasswordDate;
				$scope.details_activateLastDate     = res.data.result.activateLastDate;
				//用户真实信息
				$scope.details_userInfos_realName     = res.data.result.realName;			//真实姓名
				$scope.details_userInfos_firstName	  = res.data.result.firstName;			//姓
				$scope.details_userInfos_lastName 	  = res.data.result.lastName;			//名
				$scope.details_userInfos_identityCard = res.data.result.identityCard;		//身份证
				$scope.details_userInfos_phone        = res.data.result.phone;				//电话
				$scope.details_userInfos_mobile       = res.data.result.mobile;				//手机
				$scope.details_userInfos_sex          = res.data.result.sex;				//性别
				$scope.details_userInfos_birthday     = res.data.result.birthday;			//生日	
				$scope.details_userInfos_province     = res.data.result.province;			//省份
				$scope.details_userInfos_city         = res.data.result.city;	   			//城市
				$scope.details_userInfos_address      = res.data.result.address;			//地址
				$scope.details_userInfos_qq           = res.data.result.qq,					//qq号
				$scope.details_userInfos_postCode     = res.data.result.postCode,			//邮编
				$scope.details_userInfos_school       = res.data.result.school				//学校
			},function error(err){
				console.log(err);
			}
		);
	}
		
	var __index = 0;	
	// 修改（调用接口与“详情”相同，用于向用户展示从服务器获取的数据）
		$scope.update = function($event, $index) {
			var __index = $index
			$("#update").modal("show");
			$http({
				url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/getPusersInfo/'+$scope.userId[$index]+'',
				method : 'POST',
			}).then(function success(res) {
				// 向用户展示从服务器获取到的数据
				//$scope.userId					= res.data.result.userId[__index];
				$scope.edit_userName 			= res.data.result.userName;
				$scope.edit_displayName 		= res.data.result.displayName;
				$scope.edit_password 			= res.data.result.password;
				$scope.edit_email				= res.data.result.email;
				$scope.edit_registerSource		= res.data.result.registerSource;
				$scope.edit_portrait			= res.data.result.portrait ;
				$scope.edit_userFolder 			= res.data.result.userFolder;
				$scope.edit_status				= res.data.result.status;
				$scope.edit_isActivate			= res.data.result.isActivate;
				$scope.edit_isAutonym			= res.data.result.isAutonym;
				
				//用户真实信息
				$scope.edit_userInfos_realName     = res.data.result.realName;			//真实姓名
				$scope.edit_userInfos_firstName	   = res.data.result.firstName;			//姓
				$scope.edit_userInfos_lastName 	   = res.data.result.lastName;			//名
				$scope.edit_userInfos_identityCard = res.data.result.identityCard;		//身份证
				$scope.edit_userInfos_phone        = res.data.result.phone;				//电话
				$scope.edit_userInfos_mobile       = res.data.result.mobile;			//手机
				$scope.edit_userInfos_sex          = res.data.result.sex;				//性别
				$scope.edit_userInfos_birthday     = res.data.result.birthday;			//生日	
				$scope.edit_userInfos_province     = res.data.result.province;			//省份
				$scope.edit_userInfos_city         = res.data.result.city;	   			//城市
				$scope.edit_userInfos_address      = res.data.result.address;			//地址
				$scope.edit_userInfos_qq           = res.data.result.qq,				//qq号
				$scope.edit_userInfos_postCode     = res.data.result.postCode,			//邮编
				$scope.edit_userInfos_school       = res.data.result.school,				//学校
				$scope.userIdnew                   = res.data.result.userId
				console.log($scope.userIdnew);
			},
			function error() {

			}
		);
	}
	
	// 确认修改（用于用户修改原有的数据）
	$scope.confirmEdit = function($event) {
		// 修改角色组名、描述（封装成JSON）
		var editData = {
			userId   	   : $scope.userIdnew ,
			roleId		   : '',
			userName       : $scope.edit_userName,
			displayName    : $scope.edit_displayName,
			password       : $scope.edit_password,
			email          : $scope.edit_email,
			registerSource : $scope.edit_registerSource,
			portrait       : $scope.edit_portrait,
			userFolder     : $scope.edit_userFolder,
			status		   : $scope.edit_status,
			isActivate     : $scope.edit_isActivate,
			isAutonym      : $scope.edit_isAutonym,
			userInfos	   : {
				realName       : $scope.edit_userInfos_realName,     		//真实姓名
				firstName	   : $scope.edit_userInfos_firstName,	   		//姓
				lastName       : $scope.edit_userInfos_lastName, 	   		//名
				identityCard   : $scope.edit_userInfos_identityCard,		//身份证
				phone          : $scope.edit_userInfos_phone,        		//电话
				mobile         : $scope.edit_userInfos_mobile,       		//手机
				sex            : $scope.edit_userInfos_sex,          		//性别
				birthday       : $scope.edit_userInfos_birthday,     		//生日	
				province       : $scope.edit_userInfos_province,    		//省份
				city           : $scope.edit_userInfos_city,           		//城市
				address        : $scope.edit_userInfos_address,      		//地址
				qq             : $scope.edit_userInfos_qq,          		//qq号
				postCode       : $scope.edit_userInfos_postCode,    		//邮编
				school         : $scope.edit_userInfos_school    
			}	//学校
		}
		$http({
			url   	: $scope.zsUrl+'digitalhome-boss/admin/pusers/modify',
			method  : 'POST',
			data    : editData, /* 将JSON发送给服务器 */
		}).then(function success(res) {
			console.log(editData.userId);
			// 重新加载页面	
			//$window.location.reload();
			// 操作提示
				if( '0000' == res.data.result_code ) {
					promptCache.successPrompt(res.data.message);
					$state.go("user.personal",{},{reload:true});
					//$state.reload();
					$("#update").modal("hide");
				}else{
					promptCache.errorPrompt(res.data.message);
				}
				
			//$state.go("index.personal",{},{reload:true});
			$('#edit').modal('hide');
		},function error(err) {
			console.log(err);
		});
		
		
	}
	
	// delete enable disabled
    $scope.getDataID = function() { 
        // data length
        var len = $scope.dataID.length;
        // param id
        var whichId = 'userId';
        // param
        var deleteUrl = 'admin/pusers/delete';
        // enable disabled
        var isEnableUrl = 'admin/pusers/modifyStatus';

        // multiple selections 
        $scope.selectAll= function (bool, obj) {
            selectCache.selectAll(bool, $scope.dataID);
        };
        //  Single or multiple selections 
        $scope.select= function (selectObj, bool) {   
            var selectId = selectObj.userId;        
            selectCache.select(selectId, bool, len);    
        }; 
        
        // check
        $scope.check= function () {
            selectCache.check();
        };
        
        // delete
        $scope.delete= function () { 
            selectCache.delete(whichId, deleteUrl);
          	reloadTable();
        };

        // enable
        $scope.enable= function () {
            selectCache.isEnable(whichId, isEnableUrl, 1);
            reloadTable();
        };

        // disabled
        $scope.disabled= function () { 
            selectCache.isEnable(whichId, isEnableUrl, 0);
            reloadTable();
        };
    };
	
	// reload table
    function reloadTable() {
        $timeout(function() {
            $scope.paginationConf.onChange();
            $scope.master = false;
        },1500);
    };
    
    //原始密码
    //getPassword
    $scope.getPassword = function($index){
    	$("#password").modal("show");
    	$scope.passwordIndex = $scope.userId[$index];
    }
    
    //originalPassword
    $scope.originalPassword = function(){
    	var originalPassworddate = {
    		userId 		: $scope.passwordIndex,
    		password	: $scope.oldPassword
    	}
    	console.log($scope.passwordIndex);
    	$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/checkpw',
			method : 'POST',
			data   : originalPassworddate
		}).success(function(res) { 
			console.log(res.result_code);
			console.log(res);
			$scope.passwordcode = res.result_code;
			if($scope.passwordcode == "0000"){
				$scope.passwordcodes = true;
			}else{
				$scope.passwordcodes = false;
			}
		}).error(function(err) {
			console.log(err);
		});
    }
   	
   	//重置密码
   	//getpasswordReset
    $scope.getpasswordReset = function($index){
    	$("#passwordReset").modal("show");
    	$scope.passwordResetIndex = $scope.userId[$index];
    	$scope.userNameReset = $scope.userName[$index];
    }
    //setpasswordReset
    $scope.setpasswordReset = function(){
    	var passwordResetdate = {
    		userId 		: $scope.passwordResetIndex,
    		userName	: $scope.userNameReset
    	}
    	console.log(passwordResetdate);
    	$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/restpw',
			method : 'POST',
			data   : passwordResetdate
		}).success(function(res) { 
			if( '0000' == res.result_code ) {
				promptCache.successPrompt(res.message);
				$("#passwordReset").modal("hide");
			}else{
				promptCache.errorPrompt(res.message);
			}

		}).error(function(err) {
			console.log(err);
		});
    }
    
    //修改密码
    //updatepassword
    $scope.updatepassword = function(){
    	var updatepassworddate = {
    		userId 		: $scope.passwordIndex,
    		password	: $scope.newPassword
    	}
    	console.log(updatepassworddate);
    	$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/modifypw',
			method : 'POST',
			data   : updatepassworddate
		}).success(function(res) { 
			if( '0000' == res.result_code ) {
				promptCache.successPrompt(res.message);
				//$state.go("user.personal",{},{reload:true});
				reloadTable();
				$("#password").modal("hide");
			}else{
				promptCache.errorPrompt(res.message);
			}

		}).error(function(err) {
			console.log(err);
		});
    }
    
   	
   	//个人用户所属机构详情
   	$scope.packing = function($event, $index){
   		
   				
   		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/getInstitutions/'+$scope.userId[$index]+'',
			method : 'GET',
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8', 
			}).then(function success(res){
				console.log(res.data.result[0]);
				// console.log(res.data.result[$index].institutionId);
	
				// 向用户展示从服务器获取到的数据
				$scope.institution_institutionId 			= res.data.result[0].institutionId; 			//机构ID
				$scope.institution_institutionName 			= res.data.result[0].institutionName;			//公司名称
				$scope.institution_institutionDisplayName 	= res.data.result[0].institutionDisplayName;	//显示名称
				$scope.institution_institutionType			= res.data.result[0].institutionType;			//机构类型
				$scope.institution_institutionOrder			= res.data.result[0].institutionOrder;			//性质
				$scope.institution_industry					= res.data.result[0].industry;					//行业
				$scope.institution_province 				= res.data.result[0].province;					//省
				$scope.institution_city						= res.data.result[0].city;						//城市
				$scope.institution_address					= res.data.result[0].address;					//地址
				$scope.institution_phone					= res.data.result[0].phone;					//联系电话
				$scope.institution_contactName				= res.data.result[0].contactName;				//联机人
				$scope.institution_postcode					= res.data.result[0].postcode;					//邮编
				$scope.institution_enabled					= res.data.result[0].enabled;					//状态
	
			},function error(err){
				console.log(err);
			}
		);
   		
   	}
   	//关联角色查询
   	$scope.srs = function($event, $index){
   		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/pusers/getRolesByUserId/'+$scope.userId[$index]+'',
			method : 'GET',
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8', 
			}).then(function success(res){
				console.log(res.data);
				console.log(res.data.result[$index].institutionId);
	
				// 向用户展示从服务器获取到的数据
				$scope.institution_institutionId 			= res.data.result[$index].institutionId; 			//角色主键
				$scope.institution_institutionName 			= res.data.result[$index].institutionName;			//角色名称
	
			},function error(err){
				console.log(err);
			}
		);
   	}   	
   	//tractive
	        
}])
.directive('personalTable', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/personal/table.html',
		replace		: true,	
	}
});
});